package io.bdmc.modules.bss.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSONObject;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import io.bdmc.common.http.HttpAPIService;
import io.bdmc.common.http.HttpResult;
import io.bdmc.common.nbapi.sdk.analyze.ParsingMessage;
import io.bdmc.common.nbapi.sdk.api.online.ExecuteOpe;
import io.bdmc.common.nbapi.sdk.entity.Execute;
import io.bdmc.common.utils.Constant;
import io.bdmc.common.utils.DateUtils;
import io.bdmc.common.utils.MyMap;
import io.bdmc.common.utils.MyPage;
import io.bdmc.common.utils.R;
import io.bdmc.modules.bss.entity.SmkAlarm;
import io.bdmc.modules.bss.entity.SmkDevice;
import io.bdmc.modules.bss.model.AlarmParam;
import io.bdmc.modules.bss.service.ISmkAlarmService;
import io.bdmc.modules.bss.service.ISmkDeviceService;
import io.bdmc.modules.bss.service.ISmkShopService;
import io.bdmc.modules.sys.controller.AbstractController;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author huang lu
 * @since 2019-01-21
 */
@RestController
@RequestMapping("/bss/alarm")
public class SmkAlarmController extends AbstractController {
    @Autowired
    private ISmkAlarmService _alarmSvs;

    @Autowired
    private ISmkDeviceService _devSvs;
    @Autowired
    private ISmkShopService _shopSvs;
    @Autowired
    private HttpAPIService _apiSvs;

    @RequestMapping("/list")
    @RequiresPermissions("bss:alarm:list")
    public R list(AlarmParam params) {
        MyPage<SmkAlarm> myPage = new MyPage<SmkAlarm>(params.getCurrent(), params.getSize());
        MyPage<SmkAlarm> map = _alarmSvs.mySelectPage(myPage, params);
        return R.ok().putData(MyMap.ok(map.getRecords(), map.getTotal()));
    }

    @RequestMapping(value = "/xy")
    public R xy(@RequestBody Map<String, Long> reqMap) {
        try {
            Long deviceId = reqMap.get("deviceId");
            SmkDevice dev = _devSvs.getById(deviceId);
            if (dev == null) {
                return R.error(-1, "设备不存在。");
            }
            if (dev.getCreateBy().equals("HKAdmin")) {
                ExecuteOpe executeOpe = new ExecuteOpe();
                Execute execute = new Execute(dev.getImei(), 3339, 0, 5522);
                // 下发命令内容，JSON格式
                org.json.JSONObject body = new org.json.JSONObject();
                body.put("args", ParsingMessage.downDevData());
                String hkxyResult = executeOpe.operation(execute, body).toString();
                logger.info("hkxyResult:"+hkxyResult);
                 return R.ok("消音成功。");
            } else if (dev.getCreateBy().equals("zxyAdmin")) {
                return R.ok("消音成功。");
            } else {
                HttpResult re = null;
                if (dev.getDevModel().indexOf("H388N") != -1) {
                    re = _apiSvs.doGetCommand(dev.getDevKey(), "3541303261636463626362633432");// H388N消音
                } else {
                    re = _apiSvs.doGetCommand(dev.getDevKey(), "5859");// nb消音
                }
                String body = re.getBody();
                JSONObject json = JSONObject.parseObject(body);
                String code = json.getString("retCode");
                if (code.equals("0")) {
                    return R.ok("消音成功。");
                } else {
                    logger.error(body);
                    return R.error(-1, "消音失败。");
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
            return R.error(-1, e.getMessage());
        }
    }

    @RequestMapping(value = "/deal")
    @RequiresPermissions("bss:alarm:deal")
    public R save(@RequestBody SmkAlarm al) {
        al.setDealTime(LocalDateTime.now());
        al.setDealBy(getUser().getRealname());
        al.setAlarmStat(2);// 已处理
        boolean g = _alarmSvs.updateById(al);
        return R.trueOfFalse(g);
    }

    @RequestMapping(value = "/count")
    @RequiresPermissions("bss:alarm:list")
    public R count() {
        Long dep_id = getDeptId();
        Map<String, Object> result = new HashMap<String, Object>();
        result.put("devStc", _devSvs.wxDeviceSum(dep_id));
        result.put("alarmStc", _alarmSvs.wxAlarmSum(dep_id));
        Map<String, Object> shopMap = new HashMap<String, Object>();
        shopMap.put("total", _shopSvs.countByDepId(dep_id));
        result.put("shopStc", shopMap);
        return R.ok().putData(result);
    }

    @RequestMapping(value = "export")
    @RequiresPermissions("bss:alarm:export")
    public R downloadAllClassmate(AlarmParam params) throws IOException {
        MyPage<SmkAlarm> myPage = new MyPage<SmkAlarm>(1, 50000);
        MyPage<SmkAlarm> map = _alarmSvs.mySelectPage(myPage, params);
        List<SmkAlarm> data = map.getRecords();
        if (data.size() == 0) {
            return R.error(-1, "查询数据为空，请更改查询条件！");
        }
        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet("告警信息");
        String dateString = DateUtils.formatLocalDateTime(LocalDateTime.now(), DateUtils.FILE_DATE_PATTERN);
        String fileName = "告警信息" + dateString + ".xls";// 设置要导出的文件的名字
        // 新增数据行，并且设置单元格数据
        int rowNum = 1;
        String[] headers = { "设备名称", "安装位置", "店铺名称", "告警类型", "告警内容", "告警时间", "告警状态", "设备IMEI", "负责人", "联系方式", "处理人",
                "处理时间", "确认类型", "确认方式", "处理结果" };
        // headers表示excel表中第一行的表头
        HSSFRow row = sheet.createRow(0);
        // 在excel表中添加表头
        for (int i = 0; i < headers.length; i++) {
            HSSFCell cell = row.createCell(i);
            HSSFRichTextString text = new HSSFRichTextString(headers[i]);
            cell.setCellValue(text);
        }
        // 在表中存放查询到的数据放入对应的列
        for (SmkAlarm al : data) {
            HSSFRow row1 = sheet.createRow(rowNum);
            row1.createCell(0).setCellValue(al.getDevName() != null ? al.getDevName() : "");
            row1.createCell(1).setCellValue(al.getInstallAddr() != null ? al.getInstallAddr() : "");
            row1.createCell(2).setCellValue(al.getShopName() != null ? al.getShopName() : "");
            row1.createCell(3).setCellValue(al.getAlarmType() != null ? Constant.formAlarmType(al.getAlarmType()) : "");
            row1.createCell(4).setCellValue(al.getAlarmDetail() != null ? al.getAlarmDetail() : "");
            row1.createCell(5)
                    .setCellValue(al.getAlarmTime() != null
                            ? DateUtils.formatLocalDateTime(al.getAlarmTime(), DateUtils.DATE_TIME_PATTERN)
                            : "");
            row1.createCell(6).setCellValue(al.getAlarmStat() != null && al.getAlarmStat() == 1 ? "未确认" : "已确认");
            row1.createCell(7).setCellValue(al.getImei() != null ? al.getImei() : "");
            row1.createCell(8).setCellValue(al.getManagerName() != null ? al.getManagerName() : "");
            row1.createCell(9).setCellValue(al.getManagerMobile() != null ? al.getManagerMobile() : "");
            row1.createCell(10).setCellValue(al.getDealBy() != null ? al.getDealBy() : "");
            row1.createCell(11)
                    .setCellValue(al.getDealTime() != null
                            ? DateUtils.formatLocalDateTime(al.getDealTime(), DateUtils.DATE_TIME_PATTERN)
                            : "");
            row1.createCell(12).setCellValue(al.getDealType() != null ? Constant.formDealType(al.getDealType()) : "");
            row1.createCell(13)
                    .setCellValue(al.getDealMethod() != null ? Constant.formAlarmMethod(al.getDealMethod()) : "");
            row1.createCell(14).setCellValue(al.getDealResult() != null ? al.getDealResult() : "");
            rowNum++;
        }
        try {
            File path = new File(Constant.EXPORTPATH);
            if (!path.exists()) {
                path.mkdir();
            }
            File f = new File(path.getAbsolutePath() + "/excel/", fileName);
            if (!f.getParentFile().exists()) {
                f.getParentFile().mkdir();
            }
            FileOutputStream fileOutputStream = new FileOutputStream(f);// 指定路径与名字和格式
            workbook.write(fileOutputStream);// 将数据写出去
            fileOutputStream.close();// 关闭输出流
            return R.ok().putData("/excel/" + fileName);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error(-1, e.getMessage());
        }
    }
}
